#include "UartString.h"
#include <string.h>

UartString::UartString(/* args */):size(1024)
{
    data = new uint8_t[size];
    start = 0;
    end = 0;
}

UartString::~UartString()
{
    if (data != nullptr) {
        delete [] data;
        data = nullptr;
    }
}

UString UartString::getString()
{
    UString uString;
    uString.data = this->data + start;
    uString.length = end - start;
    return uString;
}

bool UartString::clear()
{
    start = 0;
    end = 0;
}

void UartString::addString(uint8_t* string, uint32_t len)
{
    if (string == nullptr || len <= 0) {
        return;
    }
    // SIGNWAY_LOGI("add string len = %d, start = %d, end = %d", len, start, end);
    if (end + len > size) {
        memmove(data, data + start, end - start);/* 源内存与目标内存重叠时使用memcpy会出错 */
        end = end - start;
        start = 0;
    }
    if (end + len > size) {
        clear();/* 未处理数据太多 */
    }
    memmove(data + end, string, len);
    end += len;
}

uint32_t UartString::getStart()
{
    return start;
}

bool UartString::setStart(uint32_t _start)
{
    if ((_start < 0) || (_start > size) || (_start > end)) {
        return false;
    }
    this->start = _start;
    return true;
}
